<?php

/**
 * 视图操作类
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-02
 */

namespace fw\base;

use fw\tool\Json;

class View
{
    /**
     * 连接控制器与视图
     *
     * @param string $filename 视图文件名
     * @param array  $data
     */
    public static function render($filename, $data = [])
    {
        $filename = Conf::$all['view_path'] . $filename . '.php';
        extract($data);

        // 提取内容
        $yield = self::_tplMatch($filename);

        if (!isset($yield['layout'])) {
            require $filename;
        } else {
            $layout_filename = Conf::$all['view_path'] . $yield['layout'] . '.php';

            $c_path = Conf::$all['runtime_path'] . 'view_c/';
            !is_dir($c_path) && mkdir($c_path);
            $c_filename = $c_path . MODULE_NAME . '_'
                . strtolower(Rout::gi()->currentController) . '_'
                . strtolower(Rout::gi()->currentMethod) . '_'
                . date('Ymd', time()) . '.php';

            if (!file_exists($c_filename) || filemtime($c_filename) < filemtime($filename) || filemtime($c_filename) < filemtime($layout_filename)) {

                // 生成 view_c
                $pattern = [];
                $replacement = [];
                array_shift($yield);
                foreach ($yield as $k => $v) {
                    $pattern[] = '/@yield\(\'' . $k . '\'\)/';
                    $replacement[] = $v;
                }
                $pattern[] = '/@yield\(\'\w+\'\)/';
                $replacement[] = '';

                $tplContent = file_get_contents($layout_filename);

                $c_content = preg_replace($pattern, $replacement, $tplContent);
                file_put_contents($c_filename, $c_content);

                // 内存回收
                unset($yield, $pattern, $replacement, $tplContent, $c_content);
            }

            // 引入 view_c
            require $c_filename;
        }
    }

    /**
     * 模板匹配，提取内容
     *
     * @param string $filename
     *
     * @return array
     */
    private static function _tplMatch($filename)
    {
        $tpl_content = file_get_contents($filename);

        // 取出模板
        $pattern = '/^@extends\(\'(.+)\'\)$/Um';
        preg_match($pattern, $tpl_content, $layout_matches);

        $yield = [];
        if (isset($layout_matches[1])) {
            $yield = ['layout' => $layout_matches[1]];

            // 取出内容
            $pattern = '/^@section\(\'(\w+)\'\)(.*)endsection$/sUm';
            preg_match_all($pattern, $tpl_content, $matches, PREG_SET_ORDER);

            foreach ($matches as $item) {
                $yield[$item[1]] = $item[2];
            }
            unset($matches);
        }

        return $yield;
    }

    /**
     * 错误时渲染
     *
     * @param array $resp
     * @param bool  $is_ajax
     */
    public static function error($resp = [], $is_ajax = false)
    {
        $resp = [
            'code' => isset($resp['code']) ? (int)$resp['code'] : -10000,
            'msg'  => isset($resp['msg']) ? trim($resp['msg']) : '',
            'data' => isset($resp['data']) ? (array)$resp['data'] : [],
        ];

        if ($is_ajax === true) {
            echo Json::encode($resp);
        } else {
            extract($resp);
            require __DIR__ . '/error.php';
        }
    }
}
